import * as echarts from 'echarts';
import 'echarts-gl';
// 引入新的本地 JSON 文件
import newFlightsData from '@/map/flights_sampled.json'; 
// 引入压缩过的本地图片和 HDR 文件
import starfieldImg from '@/map/starfield_compressed.jpg';
import bathymetryImg from '@/map/bathymetry_bw_composite_4k_compressed.jpg';
import lakeHdr from '@/map/lake.hdr';

const nameMapping = {
    'American Airlines': '美国港口',
    'Air China': '中国国际港口',
    'China Southern Airlines': '中国南方港口',
    'Delta Air Lines': '达美港口',
    'Ryanair': '瑞安港口',
    'China Eastern Airlines': '中国东方港口',
    'easyJet': '易捷港口',
    'United Airlines': '联合港口',
    'US Airways': '全美港口',
    'Southwest Airlines': '西南港口'
};

const initMapChart = (obj) => {
    const chart = echarts.init(obj);

    try {
        const data = newFlightsData;

        const airports = data.airports.map(function (item) {
            return {
                coord: [item[3], item[4]]
            };
        });

        function getAirportCoord(idx) {
            return [data.airports[idx][3], data.airports[idx][4]];
        }

        // Route: [airlineIndex, sourceAirportIndex, destinationAirportIndex]
        const routesGroupByAirline = {};
        data.routes.forEach(function (route) {
            const airline = data.airlines[route[0]];
            const airlineName = airline[0];
            if (!routesGroupByAirline[airlineName]) {
                routesGroupByAirline[airlineName] = [];
            }
            routesGroupByAirline[airlineName].push(route);
        });

        const pointsData = [];
        data.routes.forEach(function (airline) {
            pointsData.push(getAirportCoord(airline[1]));
            pointsData.push(getAirportCoord(airline[2]));
        });

        const series = data.airlines
           .map(function (airline) {
                const airlineName = airline[0];
                const routes = routesGroupByAirline[airlineName];
                if (!routes) {
                    return null;
                }
                const chineseName = nameMapping[airlineName] || airlineName;
                return {
                    type: 'lines3D',
                    name: chineseName,
                    effect: {
                        show: true,
                        trailWidth: 2,
                        trailLength: 0.15,
                        trailOpacity: 1,
                        trailColor: 'rgb(30, 30, 60)'
                    },
                    lineStyle: {
                        width: 1,
                        color: 'rgb(50, 50, 150)',
                        opacity: 0.1
                    },
                    blendMode: 'lighter',
                    data: routes.map(function (item) {
                        return [airports[item[1]].coord, airports[item[2]].coord];
                    })
                };
            })
           .filter(function (series) {
                return !!series;
            });

        series.push({
            type: 'scatter3D',
            coordinateSystem: 'globe',
            blendMode: 'lighter',
            symbolSize: 2,
            itemStyle: {
                color: 'rgb(50, 50, 150)',
                opacity: 0.2
            },
            data: pointsData
        });

        chart.setOption({
            legend: {
                selectedMode: 'single',
                left: 'left',
                data: Object.keys(routesGroupByAirline).map(name => nameMapping[name] || name),
                orient: 'vertical',
                textStyle: {
                    color: '#fff'
                }
            },
            globe: {
                environment: starfieldImg,
                heightTexture: bathymetryImg,
                displacementScale: 0.1,
                displacementQuality: 'high',
                baseColor: '#000',
                shading: 'realistic',
                realisticMaterial: {
                    roughness: 0.2,
                    metalness: 0
                },
                postEffect: {
                    enable: true,
                    depthOfField: {
                        enable: false,
                        focalDistance: 150
                    }
                },
                temporalSuperSampling: {
                    enable: true
                },
                light: {
                    ambient: {
                        intensity: 0
                    },
                    main: {
                        intensity: 0.1,
                        shadow: false
                    },
                    ambientCubemap: {
                        texture: lakeHdr,
                        exposure: 1,
                        diffuseIntensity: 0.5,
                        specularIntensity: 2
                    }
                },
                viewControl: {
                    autoRotate: false
                },
                silent: true
            },
            series: series
        });

        window.addEventListener('keydown', function () {
            series.forEach(function (series, idx) {
                chart.dispatchAction({
                    type: 'lines3DToggleEffect',
                    seriesIndex: idx
                });
            });
        });
    } catch (error) {
        console.error('数据处理失败:', error);
    }
};

export default initMapChart;